package com.hzhc.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @ClassName: GzipUtil
 * @Description:压缩解压缩base64工具类
 * @version 1.0
 * @author: duanhm
 * @Date: 2023/11/14 10:27:12
 * 
 */
public class GzipUtil {
	/**
	 * 使用 gzip 进行压缩
	 * 
	 * @param str 压缩前的文本
	 * @return 压缩后的文本 (BASE64 编码)
	 * @throws IOException 如果解压异常
	 */
	public static String gzip(final String str) {
		if (StrUtil.isBlank(str)) {
			return str;
		}
		String ret = null;
		byte[] compressed;
		ByteArrayOutputStream out = null;
		GZIPOutputStream zout = null;
		try {
			out = new ByteArrayOutputStream();
			zout = new GZIPOutputStream(out);
			zout.write(str.getBytes());
			zout.close();
			compressed = out.toByteArray();
			ret = new String(Base64.encode(compressed));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		return ret;
	}

	/**
	 * 使用 gzip 进行解压缩
	 * 
	 * @param compressedstr 压缩后的文本BASE64 编码
	 * @return 解压后的文本*
	 * @throws IOException 如果解压异常
	 * @return
	 */
	public static String ungzip(String compressedStr) {
		String ret = null;
		if (StrUtil.isNotBlank(compressedStr)) {
			ByteArrayOutputStream out = null;
			ByteArrayInputStream in = null;
			GZIPInputStream ginzip = null;
			try {
				out = new ByteArrayOutputStream();
				in = new ByteArrayInputStream(Base64.decode(compressedStr));
				ginzip = new GZIPInputStream(in);
				byte[] buf = new byte[1024];
				int offset = -1;
				while (-1 != (offset = ginzip.read(buf))) {
					out.write(buf, 0, offset);
				}
				out.flush();
				ret = out.toString();
			} catch (IOException e) {
				e.printStackTrace();

			} finally {
				if (ginzip != null) {
					try {
						ginzip.close();
					} catch (final IOException e) {
						e.printStackTrace();
					}
				}
				if (in != null) {
					try {
						in.close();
					} catch (final IOException e) {
						e.printStackTrace();
					}
				}
				if (out != null) {
					try {
						out.close();
					} catch (final IOException e) {
						e.printStackTrace();
					}
				}
			}
		}

		return ret;
	}

}
